package com.xunhang.controller;


import com.xunhang.entity.News;
import com.xunhang.exception.AIServiceException;
import com.xunhang.exception.ResourceNotFoundException;
import com.xunhang.repository.NewsRepository;
import com.xunhang.service.AIService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/ai")
public class AIController {

    @Autowired
    private AIService aiService;

    @Autowired
    private NewsRepository newsRepository;  // 添加这行注入

    @PostMapping("/generate-summary/{newsId}")
    public ResponseEntity<String> generateSummary(@PathVariable int newsId) {
        try {
            News news = newsRepository.findById(newsId)
                    .orElseThrow(() -> new ResourceNotFoundException("新闻不存在"));

            aiService.generateAndSaveSummary(news);
            return ResponseEntity.ok("摘要生成成功");
        } catch (AIServiceException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("摘要生成失败: " + e.getMessage());
        }
    }

    @PostMapping("/generate-all-summaries")
    public ResponseEntity<String> generateAllSummaries() {
        aiService.generateSummariesForExistingNews();
        return ResponseEntity.ok("已开始为所有新闻生成摘要");
    }
}